<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 订单模型
 *
 * @author www.dingwei.cn
 */

class DlnOrderModel extends MY_Model{
	
	public $tbUser = 'deliveryman';
	public $tbOrder = 'deliveryman_order';
	public $tbOrderLog = 'deliveryman_order_log';
	public $tbOrderAp = 'deliveryman_order_ap';
	public $tbRelationOrder = 'deliveryman_relation_order';
	
	/**
	 * 获取订单详情
	 * @param 	intger $id
	 * @param 	intger $userId
	 * @param 	bool 	$needUserInfo 是否需要配送员信息
	 * @return	array
	 */
	public function getInfo($id, $userId = 0, $needUserInfo = false, $countyId = []){
        get_instance()->loadModel('ConsumerOrderModel', 'mConOrder', 'consumer');
		$select = 'o.id,o.code,o.number,o.type,o.send_user,o.send_address,
				o.send_mobile,o.send_to_user,o.send_to_address,o.distance,o.send_to_mobile,
				o.product,o.remark,o.rob_expect_time,o.expect_arrive_time,
				o.income,o.pickup_time,o.complete_time,o.addtime,o.status,co.expect_arrive_time as consumer_expect_time,
				o.province_id,o.city_id,o.county_id,o.longitude,o.latitude,o.send_to_longitude,o.send_to_latitude';
		
		
		if($userId){
			$this->db->join($this->tbRelationOrder.' ro', 'ro.order_id = o.id')
					 ->where('ro.deliveryman_id', $userId);
		}
		
		if($needUserInfo){
			$select.= ',u.name as deliveryman,u.mobile as deliveryman_mobile,o.province_id as u_province_id,
					o.city_id as u_city_id,o.county_id as u_county_id,
					u.longitude as deliveryman_longitude,u.latitude as deliveryman_latitude,
					o.longitude,o.latitude,o.send_to_longitude,o.send_to_latitude';
			
			if( ! $countyId){
				$this->db->join($this->tbRelationOrder.' ro', 'ro.order_id = o.id', 'left')
						 ->join($this->tbUser.' u', 'u.id = ro.deliveryman_id', 'left');
			}else{
				$this->setCountyIdWhere($countyId, [2,3,4,5]);
			}
		}
		$this->db->select($select)
            ->join($this->mConOrder->tbOrder.' co', 'co.id = o.order_id')
            ->where('o.id', $id);
		
		$data = $this->getOne($this->tbOrder.' o');
		if($data){
			$data['addtime'] = dateFormat($data['addtime'], true);
			$data['expect_arrive_time'] = $data['expect_arrive_time'] ? dateFormat($data['expect_arrive_time'], true) : '';
			$data['pickup_time'] = $data['pickup_time'] ? dateFormat($data['pickup_time'], true) : '';
			$data['product'] = json_decode($data['product'], true);
			$data['complete_time'] = $data['complete_time'] ? dateFormat($data['complete_time'], true) : '';
// 			unset($data['rob_expect_time'], $data['pickup_time'], $data['status'], $data['distance']);

			if($needUserInfo){
				get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');
				$tA = $this->mSett->getLocationNameByIds([$data['province_id'], $data['city_id'], 
													$data['county_id'], $data['u_province_id'], $data['u_city_id'], $data['u_county_id']]);
				$tS = '';
				if($data['u_county_id'] > 0){
					$tS = isset($tA[$data['u_province_id']]) ? $tA[$data['u_province_id']]['name'] : '';
					$tSs = isset($tA[$data['u_city_id']]) ? $tA[$data['u_city_id']]['name'] : '';
					$tS .= $tSs == $tS ? '' : $tSs;
					$tS .= isset($tA[$data['u_county_id']]) ? $tA[$data['u_county_id']]['name'] : '';
				}else{
				
					$tS = isset($tA[$data['province_id']]) ? $tA[$data['province_id']]['name'] : '';
					$tSs = isset($tA[$data['city_id']]) ? $tA[$data['city_id']]['name'] : '';
					$tS .= $tSs == $tS ? '' : $tSs;
					$tS .= isset($tA[$data['county_id']]) ? $tA[$data['county_id']]['name'] : '';
				}
				
				$data['area'] = $tS;
				
				$data['type_str'] = $this->type($data['type']);
			}
			
			$data['status_show'] = $this->status($data['status']);
		}
		
		return $data;
	}

    /**
     * 通过订单id获取配送员信息
     * @param int $order_id
     * @return array
     * @author heyu
     */
    public function getDeliverymanInfoByOrderIds($orderIds = array()){
        if (!$orderIds){
            return array();
        }
        $this->db->select('o.order_id,o.status,u.portrait,u.name,u.mobile,ro.deliveryman_id,o.pickup_time,
                            o.complete_time,ro.addtime,u.longitude,u.latitude')
            ->join($this->tbRelationOrder.' ro', 'ro.order_id = o.id')
            ->join($this->tbUser.' u', 'ro.deliveryman_id = u.id')
            ->where_in('o.order_id', $orderIds);
        $tA = $this->getAll($this->tbOrder.' o');
        $data = array();
        foreach ($tA as $v){
            $v['addtime'] = $v['addtime']?date('m-d H:i', $v['addtime']):'';
            $v['pickup_time'] = $v['pickup_time']?date("m-d H:i", $v['pickup_time']):'';
            $v['complete_time'] = $v['complete_time']?date("m-d H:i", $v['complete_time']):'';
            $v['portrait'] = $v['portrait']? getImage($v['portrait'],'og'):getDefaultPortrait();
            $v['status_str'] = $this->status($v['status']);
            $data[$v['order_id']] = $v;
        }

        return $data;
    }

	/**
	 * 获取报备信息
	 * @param integer $id
	 * @return	array
	 */
	public function getApInfo($id){
		
		$this->db->select('type,content')
				 ->where('order_id', $id);
		$data = $this->getOne($this->tbOrderAp);
		if($data){
			$data['type'] = $this->apConfig($data['type']);
		}
		
		return $data;
	}
	
	/**
	 * 显示时间
	 *
	 * @param	$time	时间戳
	 * @return	string
	 */
	function showBeautifulTimeForMat($time, $now = 0){
	
		if( ! $time){
			return '';
		}
	
		$d = $time - ($now ? $now : time());
	
		if($d < 60){
			return floor($d).'秒内';
		}elseif($d > 60 && $d < 3600){
			return floor($d / 60).'分钟内';
		}elseif($d / 3600 < 24){
			return floor($d / 3600).'小时内';
		}elseif($d / 3600 >= 24 && $d / 3600 < 24 * 30){
			return floor($d /3600/ 24).'天内';
		}elseif($d / 3600 >= 24 * 30 && $d / 3600 < 24 * 365){
			return floor($d / 3600 / 24 / 30).'个月内';
		}elseif($d / 3600 >= 24 * 365){
			return floor($d / 3600 / 24 / 365).'年内';
		}
	
		return '';
	}
	
	/**
	 * 异常配置
	 */
	public function apConfig($key = null){
		
		$conf = [
					1 => '商家出餐不及时',
					2 => '联系不上顾客',
					3 => '顾客拒收',
					4 => '堵车、车祸',
					5 => '其他',
		];
		
		if($key){
			return isset($conf[$key]) ? $conf[$key] : '';
		}
		
		return $conf;
	}
	
	/**
	 * 获取状态显示样式
	 * @param 	integer $status
	 * @return	string
	 */
	public function status($status = null, $show = false){
	
		$config = [1 => '待接单', 2 => '待取货', 3 => '配送中', 4 => '已完成'];
		if( ! $status){
			return $config;
		}
	
		if($status && ! isset($config[$status])){
			return '';
		}
	
		if( ! $show){
			return $config[$status];
		}
	
		if($status == 1){
			return '<span class="label label-default">'.$config[$status].'</span>';
		}elseif($status == 4){
			return '<span class="label label-success">'.$config[$status].'</span>';
		}elseif($status == 3){
			return '<span class="label label-warning">'.$config[$status].'</span>';
		}elseif($status == 2){
			return '<span class="label label-info">'.$config[$status].'</span>';
		}
	
		return'';
	}
	
	/**
	 * 订单类型
	 * @param 	integer $type
	 * @return	string
	 */
	public function type($type = null){
	
		$config = [1 => '商城', 2 => '配送', 3 => '跑腿'];
		if( ! $type){
			return $config;
		}
	
		if($type && ! isset($config[$type])){
			return '';
		}
	
		return $config[$type];
	}
	
	/**
	 * 生成运单
	 * @param integer 	$storeId			店铺id
	 * @param integer 	$memberId			会员id
	 * @param integer 	$type				运单类型
	 * @param integer 	$number 			店铺订单编号
	 * @param integer 	$orderId			订单id
	 * @param integer 	$provinceId			店铺省份id
	 * @param integer 	$cityId				店铺城市id
	 * @param integer 	$countyId			店铺区县id
	 * @param number 	$longitude			店铺经度
	 * @param integer 	$latitude			店铺纬度
	 * @param string	$sendStore			店铺名称
	 * @param string 	$sendAddress		店铺详细地址
	 * @param string 	$sendMobile			店铺联系电话
	 * @param string 	$sendToUser			会员名称
	 * @param string 	$sendToMobile		会员联系电话
	 * @param string 	$sendToDddress		配送地址
	 * @param number 	$sendToLongitude	配送经度
	 * @param number 	$sendToLatitude		配送纬度
	 * @param array 	$product			产品 数组[{"name":"鱼想肉丝套饭","quantity":"2"}]
	 * @param string 	$remark				备注
	 * @param integer 	$expectArriveTime	预计送达时间（单位：分钟）
	 * @param number 	$income				预计收益
	 * @param number 	$weight				货物重量
	 * @return array
	 */
	public function add($storeId, $memberId,$type, $number, $orderId, $provinceId, $cityId, $countyId,
			$longitude, $latitude,$sendStore, $sendAddress, $sendMobile, $sendToUser, $sendToMobile,
			$sendToDddress, $sendToLongitude, $sendToLatitude, $product, $remark, $expectArriveTime,
			$income, $weight,$sendDistance){
		
		get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');		
		$config = $this->mSett->get('map_key as ak,base_distribution_fee,base_distribution_distance,base_distribution_weight
				,exceed_base_distance,exceed_base_weight,rob_expect_time,exceed_base_distance_number,exceed_base_weight_number', 'deliveryman');
//		$url = 'http://api.map.baidu.com/geocoder/v2/?address='.$sendAddress.'&output=json&ak='.$config['ak'];
//
//		$tA = $this->_request($url);
//
//		if($tA == false){
//			return ['status' => 0, 'message' => '地址解析错误'];
//		}

//		$tS = getDistance($latitude, $longitude, $tA[0], $tA[1]);
//		if( ! is_numeric($tS) || $tS > 100){
//			return ['status' => 0, 'message' => '店铺地址有误差:'.$tS];
//		}
		
//		$url = 'http://api.map.baidu.com/geocoder/v2/?address='.$sendToDddress.'&output=json&ak='.$config['ak'];
//		$tA = $this->_request($url);
//
//		if($tA == false){
//			return ['status' => 0, 'message' => '地址解析错误'];
//		}

//		$tS = dsitance($sendToLatitude, $sendToLongitude, $tA[0], $tA[1]);

//		if( ! is_numeric($tS) || $tS > 100){
//			return ['status' => 0, 'message' => '送货地址有误差'];
//		}

		$distance = dsitance($latitude, $longitude, $sendToLatitude, $sendToLongitude);
//
//		$tIncome = $this->getIncome($distance / 1000, $weight, $config);

//		if($tIncome != $income){
//			return ['status' => 0, 'message' => '配送费发生了变化，请重新下单'];
//		}
		
		$code = uniqid().rand(1000,9999).rand(1000,9999);
		$this->db->where('order_id', $orderId);
		$tI = $this->count($this->tbOrder);
		if($tI > 0){
			return ['status' => 0, 'message' => '该订单已生成了运单'];
		}
		
		$dbData = [
					'store_id' => $storeId,
					'member_id' => $memberId,
					'type' => $type,
					'code' => $code,
					'number' => $number,
					'order_id' => $orderId,
					'province_id' => $provinceId,
					'city_id' => $cityId,
					'county_id' => $countyId,
					'longitude' => $longitude,
					'latitude' => $latitude,
					'weight' => $weight,
					'send_user' => $sendStore,
					'send_address' => $sendAddress,
					'send_mobile' => $sendMobile,
					'send_to_user' => $sendToUser,
					'send_to_address' => $sendToDddress,
					'send_to_longitude' => $sendToLongitude,
					'send_to_latitude' => $sendToLatitude,
					'distance' => $sendDistance,
					'send_to_mobile' => $sendToMobile,
					'product' => json_encode($product),
					'remark' => $remark,
					'rob_expect_time' => time() + $config['rob_expect_time'] * 60,
					'order_month' => date('Ymd', time() + $expectArriveTime * 60),
					'income' => $income,
					'expect_arrive_time' => time() + $expectArriveTime * 60,
					'pickup_time' => 0,
					'complete_time' => 0,
					'status' => 1,
					'addtime' => time(),
		];

		if( ! $id = $this->insert($this->tbOrder, $dbData)){
			return ['status' => 0, 'message' => '运单生成失败'];
		}
		
		if( ! $this->addLog($id, '')){
		    return ['status' => 0, 'message' => '运单日志失败'];
		}
		
		return ['status' => 1, 'message' => ''];
	}
	
	/**
	 * 添加运单日志
	 */
	public function addLog($id, $description){
	    
	    $data = ['order_id' => $id, 'description' => $description, 'addtime' => time()];
	    if($this->insert($this->tbOrderLog, $data)){
	        return true;
	    }
	    
	    return false;
	}
	
	/**
	 * 获取收益
	 * @param number $dsitance	距离（km）
	 * @param number $weight	重量（kg）
	 * @param array $config		配置
	 * @return number
	 */
	public function getIncome($dsitance, $weight, $config = null){

		if($config == null){
			get_instance()->loadModel('AdmSettingModel', 'mSett', 'admin');
			$config = $this->mSett->get('base_distribution_fee,base_distribution_distance,base_distribution_weight
				,exceed_base_distance,exceed_base_weight,exceed_base_distance_number,exceed_base_weight_number', 'deliveryman');
		}
		
		$tIncome = $config['base_distribution_fee'];
		if($config['base_distribution_distance'] > 0 && $dsitance > $config['base_distribution_distance']){
			$tIncome += (ceil(($dsitance - $config['base_distribution_distance']) / $config['exceed_base_distance_number']) * $config['exceed_base_distance']);
		}

		if($config['base_distribution_weight'] > 0 && $weight > $config['base_distribution_weight']){
			$tIncome += ((($weight - $config['base_distribution_weight']) / $config['exceed_base_weight_number']) * $config['exceed_base_weight']);
		}

		return $tIncome;
	}
	
	/**
	 * 请求接口
	 *
	 * @param	string	$url	请求路径
	 * @param 	array 	$param	请求参数
	 */
	public function _request($url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_POST, false);
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		$data = curl_exec($curl);
		if(curl_errno($curl)){
//			p(curl_error($curl));
			exit(json_encode(array('status' => 0, 'data' => NULL, 'message' => curl_error($curl)), JSON_UNESCAPED_UNICODE));
		}
		curl_close($curl);
		$tA = json_decode($data, true);
		if( ! is_array($tA) || ! isset($tA['status']) || $tA['status'] != 0){
			return false;
		}

		return [$tA['result']['location']['lat'], $tA['result']['location']['lng']];
	}
	
	/**
	 * 根据区域获取订单数量
	 * @param 	String 	$countyId
	 * @param 	integer $status
	 * @return	array
	 */
	public function getTodayCount($countyId, $status){
		
		$time = strtotime(date('Y-m-d'));
	
		$this->db->where('o.addtime >=', $time);
		$this->setCountyIdWhere($countyId, [2,3,5]);
		if($status > 0){
			$this->db->where('o.status', $status);
		}

		return $this->mOrder->count($this->mOrder->tbOrder.' o');
	}
	
	/**
	 * 根据区域获取订单数量
	 * @param 	String 	$countyId
	 * @param 	integer $status
	 * @return	array
	 */
	public function getTodayCountBuyDeliverymanId($id, $status = 0){
	    
	    $time = strtotime(date('Y-m-d'));
	    
	    $this->db->where('o.addtime >=', $time)
	             ->join($this->tbRelationOrder.' ro', 'ro.order_id = o.id')
	             ->where('ro.deliveryman_id', $id);
	    if($status > 0){
	        $this->db->where('o.status', $status);
	    }
	    return $this->mOrder->count($this->mOrder->tbOrder.' o');
	}
	
	/**
	 * 添加区域条件筛选
	 * @param 	array 	$CountyId	区域id
	 * @param 	array 	$status		状态
	 * @return	void
	 */
	
	public function setCountyIdWhere($countyId, $status){
		
		$this->db->join($this->mOrder->tbRelationOrder.' ro', 'ro.order_id = o.id', 'left')
				 ->join($this->mMember->tbUser.' u', 'u.id = ro.deliveryman_id', 'left')
				 ->where('((o.status = 1 and o.county_id in ('.implode($countyId, ',').'))
				 		or (o.status in ('.implode(',', $status).')
				 		and u.county_id in ('.implode(',' ,$countyId).')))');
	}
}